package com.lgc.webtest.util;

import com.google.gson.*;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.Date;

public class JsonUtil {
    /* 默认的 {@code JSON} 日期/时间字段的格式化模式,精确到毫秒 */
    public static final String DEFAULT_DATE_PATTERN = "yyyy-MM-dd HH:mm:ss";// "yyyy-MM-dd HH:mm:ss SSS"

    public static String toJson(Object obj)
    {
        if(obj==null)
        {
            return "{}";
        }

        GsonBuilder builder = new GsonBuilder();
        builder.setDateFormat(DEFAULT_DATE_PATTERN);
        Gson gson = builder.create();
        return gson.toJson(obj);
    }

    /**
     * T是不含泛型时,如CompetitionDto
     * @param json
     * @param classOfT
     * @param <T>
     * @return
     */
    public static <T> T fromJson(String json,Class<T> classOfT)
    {
        if (isEmpty(json)) {
            return null;
        }

        Gson gson=new Gson();
        return gson.fromJson(json,classOfT);
    }

    /**
     * T是含泛型时,如ResponseDto<CompetitionDto>
     * @param json
     * @param typeOfT
     * @param <T>
     * @return
     */
    public static <T> T fromJson(String json,Type typeOfT,boolean isTimeStamp)
    {
        if (isEmpty(json)) {
            return null;
        }

        GsonBuilder builder = new GsonBuilder();

        if (isTimeStamp==false) {
            // 时间yyyy-MM-dd HH:mm:ss戳转Date
            builder.setDateFormat(DEFAULT_DATE_PATTERN);
        }else {
            // 时间戳转Date
            builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
                @Override
                public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
                    return new Date(json.getAsJsonPrimitive().getAsLong());
                }
            });
        }

        Gson gson = builder.create();
        return gson.fromJson(json, typeOfT);
    }

    public static <T> T fromJson(String json, TypeToken<T> token) {
        return fromJson(json,token.getType(),false);
    }

    public static <T> T fromJson(String json, TypeToken<T> token,boolean isTimeStamp) {
        return fromJson(json,token.getType(),isTimeStamp);
    }

    private static boolean isEmpty(String json) {
        return json == null || json.trim().length() == 0;
    }
}
